﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Sol_Demo.Api.Models;
using Sol_Demo.Api.Service;

namespace Sol_Demo.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        IService service;
        public LoginController(IService Service)
        {
            service = Service;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="param">param</param>
        /// <returns></returns>
        [HttpPost("Login")]
        public async Task<IActionResult> Login([FromBody]User param)
        {

            //ResponseModel response = new ResponseModel()
            //{
            //    RESULT = true,
            //    MESSAGE = "成功",
            //    RESPONSE = "成功"
            //};


            var result = await service.Login(param);

            ResponseModel response = new ResponseModel()
            {
                RESULT = result.Count() == 1 ? true : false,
                MESSAGE = result.ToList().Count == 1 ? "成功" : "失败",
                RESPONSE = result
            };

            return Ok(response);
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="param">param</param>
        /// <returns></returns>
        [HttpPost("Register")]
        public IActionResult Register([FromBody]User param)
        {

            try
            {
                //验证用户是否已注册
                var result = service.Validate(param);
                if (result != 0)
                {
                    return Ok(new ResponseModel()
                    {
                        RESULT = result == 0 ? true : false,
                        MESSAGE = result == 0 ? "成功" : "失败",
                        RESPONSE = "该用户名已被注册！"
                    });
                }


                param.ID = Guid.NewGuid().ToString();
                result = service.Register(param);

                ResponseModel response = new ResponseModel()
                {
                    RESULT = result == 1 ? true : false,
                    MESSAGE = result == 1 ? "成功" : "失败",
                    RESPONSE = result
                };

                return Ok(response);
            }
            catch (Exception ce)
            {
                return Ok(new ResponseModel()
                {
                    RESULT = false,
                    MESSAGE = "失败",
                    RESPONSE = "注册失败！"
                });
            }
        }

    }
}